package com.lanou.musicbox.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.lanou.musicbox.R;
import com.lanou.musicbox.activity.MainActivity;
import com.lanou.musicbox.base.BaseApplication;
import com.lanou.musicbox.custom.Events;
import com.lanou.musicbox.entity.Entity;
import com.lanou.musicbox.fragment.IMusicBackService;
import com.lanou.musicbox.lrc.LyricDownloadManager;
import com.lanou.musicbox.utils.Contant;
import com.lanou.musicbox.utils.MyConfig;
import com.lanou.musicbox.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/10/21.
 */
public class MusicService extends Service {
    // 定义一个播放对象
    private MediaPlayer mMediaPlayer;
    private List<Entity> mList;
    private int position;
    private String songs_link, songLrcLink, bg_music, songs_lrc;
    private int mNowPlayIndex = 0;
    private VolleySingleton volleySingleton;
    private Events.MusicInfoEvent musicInfoEvent;
    private boolean isFirst = false;//是否是第一次放歌
    private LyricDownloadManager downloadManager;
    private Handler handler = new Handler();
    public static final String ALARM_CLOCK_BROADCAST = "alarm_clock_broadcast";

    private boolean DANQU = true;
    // 播放模式
    public static final int MPM_LIST_LOOP_PLAY = 0; // 列表循环

    public static final int MPM_RANDOM_PLAY = 1; // 随机播放
    public static final int MPM_SINGLE_LOOP_PLAY = 2; // 单曲循环
    private int model;
    private int random;
    private int key_this;
    private String whatMusics = "本地";
    private Events.NewSongsEvent songsEvent;
    private String lyricFilePath;
    private Notification notification;
    private RemoteViews contentView;
    private String bottom_pause;

    private File lyricfile;
    private BaseApplication application;
    public NotificationManager notManager ;
    private Mp3Receiver mp3Receiver;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub

        return mBinder;
    }

    public void onEvent(Events.MusicInfoEvent musicInfoEvent) {
        whatMusics = musicInfoEvent.getWhatMusic();
        mList = musicInfoEvent.getMp3Infos();
        if (whatMusics.equals("网络")) {
            position = mList.get(0).getItem_id();
            mNowPlayIndex = position;
            Log.i("sysom", ">>>>>>>>1_网络" + mNowPlayIndex);
            analysisSongs(mNowPlayIndex);

        } else if (whatMusics.equals("天天动听")) {
            position = mList.get(0).getItem_id();
            mNowPlayIndex = position;
            setDataSource();
            Log.i("sysom", ">>>>>>>>1_天天动听" + mNowPlayIndex);
        }

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.i("lanou4646556", "run_bus1 "+mList.size());
            //if (mMediaPlayer.isPlaying()) {
                handler.postDelayed(runnable, 500);
                //if (mMediaPlayer != null) {
                    Log.i("lanou4646556", "run_bus "+mList.size());
                    songsEvent.setMp3Infos(mList, whatMusics);
                    EventBus.getDefault().post(songsEvent);
               // }
            }


       // }
    };

    public void analysisSongs(int key) {
        key_this = key;


        lyricFilePath = LyricDownloadManager.lrcPath + "/" + mList.get(key_this).getTitle() + ".lrc";
        lyricfile = new File(lyricFilePath);

        String songs_id = mList.get(key).getSongs_id();
        String songs_id_Url = Contant.Url.URL_SONGS_LINK_Frist +
                songs_id + Contant.Url.URL_SONGS_LINK_Second;
        JsonObjectRequest jr = new JsonObjectRequest(songs_id_Url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject songurl = response.getJSONObject("songurl");
                    JSONObject songinfo = response.getJSONObject("songinfo");
                    JSONArray url = songurl.getJSONArray("url");
                    JSONObject url_1 = url.getJSONObject(1);
                    songs_link = url_1.getString("file_link");
                    bg_music = songinfo.getString("artist_1000_1000");
                    songs_lrc = songinfo.getString("lrclink");
                    if (mList != null && mNowPlayIndex < mList.size()) {
                        mList.get(mNowPlayIndex).setUrl(songs_link);
                        mList.get(mNowPlayIndex).setBig_pic(bg_music);
                    }
                    if (!lyricfile.exists()) {
                        // 本地没有有歌词，从网络下载
                        if (songs_lrc != null) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    String SongsName = mList.get(key_this).getTitle();
                                    downloadManager.fetchLyricContent(SongsName, songs_lrc);
                                    Log.i("lanou3499", "analysisSongs_songsLink2 " + SongsName);
                                }
                            }).start();
                        }
                    }

                   // Log.i("sysom", ">>>>>>>>2_网络" + mNowPlayIndex);
                    setDataSource();

                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.i("lanou3333333", "onResponse " + "解析出错");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        volleySingleton.addQueue(jr);

    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        notManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mp3Receiver = new Mp3Receiver();
        mMediaPlayer = new MediaPlayer();
        EventBus.getDefault().register(this);
        downloadManager = new LyricDownloadManager();
        volleySingleton = VolleySingleton.getInstance(getApplicationContext());
        musicInfoEvent = new Events.MusicInfoEvent();
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mMediaPlayer.start();
                Log.i("lanou", "----->>>>221");
            }
        });
        songsEvent = new Events.NewSongsEvent();
        //注册 EventBus

        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction(ALARM_CLOCK_BROADCAST);//闹钟广播接受者
        this.registerReceiver(mAlarmReceiver, intentFilter1);
        //initNotificationBar();
        super.onCreate();
    }

    @SuppressLint("NewApi")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        if (mMediaPlayer.isPlaying()) {
            sendReceiverUpdateUI();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    // 设置加载资源
    void setDataSource() {
        isFirst = true;
        handler.postDelayed(runnable, 500);
        model = MyConfig.getSharePreInt(this, "which_mode", "chooseMode");
        Log.i("lanou895985", "setDataSource " + model);
        if (mList.get(mNowPlayIndex).getUrl() != null) {
            try {
                mMediaPlayer.reset(); // 重新实例化
                Log.i("lanou6666666", "playNextMusic_mNowPlayIndex2 " + mNowPlayIndex);
                Log.i("sysom", ">>>>>>>>3_网络" + mNowPlayIndex);
                mMediaPlayer.setDataSource(mList.get(mNowPlayIndex).getUrl()); //设置需要加载的文件
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // 设置音频流
                mMediaPlayer.prepareAsync();
            } catch (IOException ex) {
                // TODO: notify the user why the file couldn't be opened
                return;
            } catch (IllegalArgumentException ex) {
                // TODO: notify the user why the file couldn't be opened
                return;
            }
            mMediaPlayer.setOnCompletionListener(mMusicCompletionListener);
            sendReceiverUpdateUI();
        } else {
            playNextMusic();
            sendReceiverUpdateUI();
        }

    }

    MediaPlayer.OnCompletionListener mMusicCompletionListener =
            new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer arg0) {
                    // TODO Auto-generated method stub
                    Log.i("sysom", ">>>>>>>>4_网络" + mNowPlayIndex);
                    if (model == MPM_SINGLE_LOOP_PLAY) {
                        setDataSource();
                    } else {
                        playNextMusic();
                    }

                }
            };

    //产生随机数的方法
    public int randNumber() {
        Random random = new Random();
        int rand = random.nextInt(mList.size());
        return rand;
    }

    private void setRandom(int indext) {
        model = indext;
        Log.i("lou3q", "————————————————22  " + indext);
        switch (indext) {
            case MPM_LIST_LOOP_PLAY:
                break;
            case MPM_RANDOM_PLAY:
                break;
            case MPM_SINGLE_LOOP_PLAY:
                Log.i("sysom", " 是否为单曲 " + indext);
                singleModel();
                break;
        }

    }

    private void singleModel() {
        mMediaPlayer.setLooping(DANQU);
    }

    /**
     * 播放下一曲歌曲
     */

    private void playNextMusic() {

        switch (model) {
            case MPM_LIST_LOOP_PLAY://顺序播放

                if (mList != null && !mList.equals("") && mList.size() > 0) {
                    if (mNowPlayIndex + 1 > mList.size() - 1) {
                        Log.i("lou3q", "————————————————44   " + mNowPlayIndex);
                        mNowPlayIndex = 0;
                    } else {
                        mNowPlayIndex++;
                        Log.i("lanou6666666", "playNextMusic_mNowPlayIndex1 " + mNowPlayIndex);
                    }
                    if (whatMusics != null && whatMusics.equals("网络")) {
                        analysisSongs(mNowPlayIndex);
                        Log.i("sysom", ">>>>>>>>下_循环_网络" + mNowPlayIndex);
                    } else {
                        Log.i("sysom", ">>>>>>>>下_循环_本地" + mNowPlayIndex);
                        setDataSource();
                    }
                }
                break;
            case MPM_RANDOM_PLAY://随机播放
                random = randNumber();
                if (mList != null && !mList.equals("") && mList.size() > 0) {
                    if (random <= mList.size() && random >= 0) {
                        mNowPlayIndex = random;

                        if (whatMusics != null && whatMusics.equals("网络")) {

                            if (random <= mList.size() && random >= 0) {
                                analysisSongs(mNowPlayIndex);
                                Log.i("sysom", ">>>>>>>>随机_网络" + mNowPlayIndex);
                            }
                        } else {
                            setDataSource();
                            Log.i("sysom", ">>>>>>>>随机_本地" + mNowPlayIndex);
                        }
                    }
                }
                break;
            case MPM_SINGLE_LOOP_PLAY://单曲循环
                mNowPlayIndex++;
                setDataSource();

        }
    }

    private void playUpMusic(){  //上一曲
        if (model == MPM_LIST_LOOP_PLAY) {
            if (mList != null && !mList.equals("") && mList.size() > 0) {
                if (mNowPlayIndex - 1 < 0) {
                    mNowPlayIndex = mList.size() - 1;
                } else {
                    mNowPlayIndex--;
                    Log.i("lanou6666666", "playNextMusic_m " + mNowPlayIndex);
                }
                if (whatMusics.equals("网络")) {
                    analysisSongs(mNowPlayIndex);
                } else {
                    setDataSource();
                }
            }
        } else if (model == MPM_RANDOM_PLAY) {
            random = randNumber();
            Log.i("sysom", ">>>>>>>>1" + random);
            if (random <= mList.size() && random >= 0) {
                mNowPlayIndex = random;

            } else {
                mNowPlayIndex++;
            }
            setDataSource();
        } else if (model == MPM_SINGLE_LOOP_PLAY) {
            Log.i("sysom", "playSingleMusic_m " + mNowPlayIndex);
            setDataSource();
        }
    }

    /**
     * 取消睡眠闹钟
     */
    private void cancleSleepClocks() {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MusicService.this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pendingIntent);
        BaseApplication.IS_SLEEP_CLOCK = false;
    }

    /**
     * 设置睡眠闹钟
     *
     * @param times
     */
    public void setSleepClocks(String times) {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MusicService.this, 0, intent, 0);
        // 设置time时间之后退出程序
        int time = Integer.parseInt(times);
        long longTime = time * 60 * 1000L;
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + longTime,
                pendingIntent);
        BaseApplication.IS_SLEEP_CLOCK = true;



    }

    /**
     * 更新 UI 的广播
     */

    private void sendReceiverUpdateUI() {
        Intent i = new Intent(MainActivity.UPDATE_UI);
        sendBroadcast(i);
    }
    /**
     * 定义闹钟广播接收者
     **/
    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("lanou99999999999", "close");
            stopService(new Intent(context, MusicService.class));
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
    };

    /**
     * 实现aidl的接口
     */
    private final IMusicBackService.Stub mBinder = new IMusicBackService.Stub() {
        // 返回当前播放到位置
        @Override
        public String getNowPlayingMusicCurTime() throws RemoteException {
            // TODO Auto-generated method stub
            return formatTime((long) mMediaPlayer.getCurrentPosition());
        }

        // 返回当前音频长度
        @Override
        public String getNowPlayingMusicMaxTime() throws RemoteException {
            // TODO Auto-generated method stub
            Log.i("lanou8888888000", "getNowPlayingMusicMaxTime " + mMediaPlayer.getDuration());
            return formatTime(mMediaPlayer.getDuration());
        }

        @Override
        public int getNowPlayingMaxTime() throws RemoteException {
            return mMediaPlayer.getDuration();
        }

        @Override
        public int getNowPlayingCurTime() throws RemoteException {
            return mMediaPlayer.getCurrentPosition();
        }

        //是否在放音乐
        @Override
        public boolean getMusicIsPlaying() throws RemoteException {
            // TODO Auto-generated method stub
            return mMediaPlayer.isPlaying();
        }

        // 暂停播放
        @Override
        public void stopMusic() throws RemoteException {
            // TODO Auto-generated method stub
            System.out.println("start");
            mMediaPlayer.stop();
            initNotificationBar();
        }

        // 开始播放
        @Override
        public void playMusic() throws RemoteException {
            // TODO Auto-generated method stub
            System.out.println("start");
            if (mList != null && !mList.equals("") && mList.size() > 0) {
                if (!isFirst) {
                    setDataSource();
                }
                mMediaPlayer.start();
                initNotificationBar();

            }
            Log.i("sysom", ">>>>>>>>" + mList.get(mNowPlayIndex).getTitle());
        }

        /**
         *
         * @throws RemoteException
         */
        @Override
        public void playUpMusic() throws RemoteException {//上一曲
            // TODO Auto-generated method stub
            playUpMusic();
            initNotificationBar();
        }

        // 播放下一首
        @Override
        public void PlayNextMusic() throws RemoteException {
            // TODO Auto-generated method stub
            playNextMusic();
            initNotificationBar();
        }

        //暂停
        @Override
        public void pauseMusic() throws RemoteException {
            if (mList != null && !mList.equals("") && mList.size() > 0) {
                mMediaPlayer.pause();
            }

        }

        //
        @Override
        public void setNowPlay(int time) throws RemoteException {
            // TODO Auto-generated method stub
            if (whatMusics != null && whatMusics.equals("网络")) {
                mNowPlayIndex = time;
                analysisSongs(mNowPlayIndex);
            }
            mNowPlayIndex = time;
        }

        //获得当前播放的歌曲 id
        @Override
        public int getNowPlay() throws RemoteException {
            // TODO Auto-generated method stub
            return mNowPlayIndex;
        }

        //设置新的播放内容
        @Override
        public void setDataSourceAndPlay() throws RemoteException {
            // TODO Auto-generated method stub
            if (mList != null && !mList.equals("") && mList.size() > 0) {
                setDataSource();
            }
        }

        //跳到播放的位置
        @Override
        public void setProgress(int progress) throws RemoteException {
            // TODO Auto-generated method stub
            mMediaPlayer.seekTo(progress);
        }

        @Override
        public void singglePlay() throws RemoteException {
            singleModel();

        }

        @Override
        public void setRandomPlay(int i) throws RemoteException {
            setRandom(i);
        }

        @Override
        public String getBgMusic() throws RemoteException {
            if (bg_music != null) {

                return bg_music;
            }
            return null;
        }
        //设置闹钟的时间
        @Override
        public void setSleepClock(String times) throws RemoteException {
            setSleepClocks(times);
        }
        //取消闹钟的设置
        @Override
        public void cancleSleepClock() throws RemoteException {
            cancleSleepClocks();
        }
    };

    @Override
    public void onDestroy() {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    //把时间毫秒转换成分钟,秒
    public static String formatTime(long time) {                     //将歌曲的时间转换为分秒的制度
        String min = time / (1000 * 60) + "";
        String sec = time % (1000 * 60) + "";

        if (min.length() < 2)
            min = "0" + min;
        switch (sec.length()) {
            case 4:
                sec = "0" + sec;
                break;
            case 3:
                sec = "00" + sec;
                break;
            case 2:
                sec = "000" + sec;
                break;
            case 1:
                sec = "0000" + sec;
                break;
        }
        return min + ":" + sec.trim().substring(0, 2);
    }
    /**
     * 音乐通知栏
     *
     */
    public void initNotificationBar() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        notification = new Notification();
        //初始化通知
        notification.icon = R.mipmap.music_icon_green;
        contentView = new RemoteViews(getPackageName(),
                R.layout.notification_music);
        String songs_name = mList.get(mNowPlayIndex).getTitle();
        String singer_name = mList.get(mNowPlayIndex).getArtist();
        contentView.setTextViewText(R.id.bottom_title,songs_name);
        contentView.setTextViewText(R.id.bottom_singer,singer_name);


//        if (mMediaPlayer.isPlaying()){
//            contentView.setImageViewResource(R.id.bottom_pause, R.drawable.bt_pause_music);
//        }
//        else {
//            contentView.setImageViewResource(R.id.bottom_pause,R.drawable.bt_play_music);
//        }

        notification.contentView = contentView;

//        Intent intentPlay = new Intent("play");//新建意图，并设置action标记为"play"，用于接收广播时过滤意图信息
//        PendingIntent pIntentPlay = PendingIntent.getBroadcast(this, 0,
//                intentPlay, 0);
//        contentView.setOnClickPendingIntent(R.id.bottom_pause, pIntentPlay);//为play控件注册事件,播放或暂停
//
//        Intent intentPause = new Intent("pause");
//        PendingIntent pIntentPause = PendingIntent.getBroadcast(this, 0,
//                intentPause, 0);
//        contentView.setOnClickPendingIntent(R.id.bottom_pause, pIntentPause);
//
//        Intent intentNext = new Intent("next");
//        PendingIntent pIntentNext = PendingIntent.getBroadcast(this, 0,
//                intentNext, 0);
//        contentView.setOnClickPendingIntent(R.id.bottom_next, pIntentNext);
//
//        Intent intentLast = new Intent("last");
//        PendingIntent pIntentLast = PendingIntent.getBroadcast(this, 0,
//                intentLast, 0);
//        contentView.setOnClickPendingIntent(R.id.bottom_up, pIntentLast);

//        Intent intentCancel = new Intent("cancel");
//        PendingIntent pIntentCancel = PendingIntent.getBroadcast(this, 0,
//                intentCancel, 0);
//        contentView
//                .setOnClickPendingIntent(R.id.bt_notic_cancel, pIntentCancel);

//        mBuilder.setContent(contentView)
//               // .setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT))
//                .setWhen(System.currentTimeMillis())// 通知产生的时间，会在通知信息里显示
//                .setTicker("正在播放")
//                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
//                .setOngoing(true)
//                .setSmallIcon(R.mipmap.music_icon_green);
//        Notification notify = mBuilder.build();

    //    notification.flags = notification.FLAG_NO_CLEAR;//设置通知点击或滑动时不被清除
        notManager.notify(100, notification);//开启通知

    }

    public class Mp3Receiver extends BroadcastReceiver {
        private BaseApplication application;
        //private IMusic music;

        @Override
        public void onReceive(Context context, Intent intent) {

            application = (BaseApplication) context.getApplicationContext();
            String ctrl_code = intent.getAction();//获取action标记，用户区分点击事件

            Log.i("guangbo_", "onReceive_121 ");
           // music = application.music;//获取全局播放控制对象，该对象已在Activity中初始化
            //if (music != null) {
//                if ("play".equals(ctrl_code)) {
//                    mMediaPlayer.start();
//                    System.out.println("play");
//                } else if ("pause".equals(ctrl_code)) {
//                    mMediaPlayer.pause();
//                    System.out.println("pause");
//                } else if ("next".equals(ctrl_code)) {
//                    playNextMusic();
//                    System.out.println("next");
//                } else if ("last".equals(ctrl_code)) {
//                    playUpMusic();
//                    System.out.println("last");
//                }
            }

//            if ("cancel".equals(ctrl_code)) {
//                application.notManager.cancel(Const.NOTI_CTRL_ID);
//                System.exit(0);
//            }
//        }

    }


}
